<template>
    <van-sticky>
        <van-nav-bar title="榜单排行" left-text="返回" left-arrow @click-left="onBack" />
    </van-sticky>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
        <!-- 加载列表 -->
        <van-list v-model:loading="loading" :finished="finished" :offset="10" :immediate-check="true"
            finished-text="没有更多了" @load="onLoad">
            <!-- 商品卡片 -->
            <van-card v-for="(item, key) in list" :thumb="item[0].thumb_cdn" :key="key" @click="btn(item[0].id)">
                <template #title>
                    <div class="title">排名：{{ key+1 }}</div>
                </template>
                
                <template #tags>
                    <div class="tags">商品：{{ item[0].name }}</div>
                </template>

                <template #price>
                    <div class="price">￥{{ item[0].price }}/
                        {{ item[0].unitid == 1 ? "个" : item[0].unitid == 3 ? "张" : "台" }}</div>
                </template>
            </van-card>
        </van-list>
    </van-pull-refresh>
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = ref(proxy.$cookies.get('business') ?? {});
const list = ref([]);
const refreshing = ref(false);
const page = ref(1); //当前页面数
const listCount = ref(0); //订单个数

const onRefresh = () => {
    list.value = [];
    page.value = 1;
    finished.value = false;
    loading.value = true;

    setTimeout(onLoad, 1500);
};

const loading = ref(false);   //关闭懒加载状态
const finished = ref(false); //判断是否已下拉加载完成的状态,true完成，false没有

//懒加载
const onLoad = async () => {
    if (refreshing.value) {
        refreshing.value = false;
    }

    let result = await proxy.$post({
        url: '/product/product/top'
    })

    if (result.code === 1) {
        list.value = result.data.list;
        listCount.value = result.data.count;
        finished.value = false;
        loading.value = false;

        if (list.value.length === listCount.value) {
            finished.value = true;

            return false;
        }
        page.value = page.value + 1;
    } else {
        proxy.$showToast(result.msg);
        finished.value = true;
    }
}

//跳转页面
const btn = (proid) => proxy.$router.push({ path: '/product/product/info', query: { proid } });

const onBack = () => {
    proxy.$cookies.remove('attrs');
    proxy.$router.back();
}
</script>

<style scoped>
.van-image{
    width: 300px;
    height: 200px;
}
</style>